package com.itheima.exam;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.UUID;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TCPServer {
    public static void main(String[] args) throws IOException {
        //创建服务器对象
        ServerSocket serverSocket = new ServerSocket(8888);

        //创建线程池
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                5,//核心线程数
                10,//总线程数
                2,//临时线程消亡时间
                TimeUnit.SECONDS,//时间单位
                new ArrayBlockingQueue<>(10),//阻塞队列
                Executors.defaultThreadFactory(),//创建线程方式
                new ThreadPoolExecutor.AbortPolicy()//拒绝策略
        );

        while (true){
            //监听端口，收到消息就获得socket对象，accept()是阻塞的
            Socket socket = serverSocket.accept();
            //创建线程对象
            Thread t = new Thread(new MyThread(socket));
            //添加到线程池执行
            pool.submit(t);
        }

        //serverSocket.close();
    }
}

class MyThread implements Runnable{
    private Socket socket;
    public MyThread(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            //获得网络输入流
            InputStream is = socket.getInputStream();
            //转成字节输入缓冲流
            BufferedInputStream bis = new BufferedInputStream(is);

            //获取本地字节输出流，将接收的文件保存到本地
            //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day15_inter\\copy\\"+ UUID.randomUUID()+".jpg"));
            String[] split = UUID.randomUUID().toString().split("-");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("day15_inter\\copy\\"+ split[0]+".jpg"));
            int b;
            //读接收到的数据
            while ((b = bis.read())!=-1){
                //写入本地文件
                bos.write(b);
            }

            //获取网络输出流
            OutputStream os = socket.getOutputStream();
            //转成字符缓冲输出流
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            //输出数据
            bw.write("上传成功");
            //刷新
            bw.flush();
            //关闭
            bw.close();

            //关闭字节输入流
            bis.close();
            //关闭本地字节输出流
            bos.close();
            //关闭socket对象
            socket.close();
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
